package com.scen.upload.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.EnumMap;

/**
 * @author Administrator
 * @title: ZxingCodeEncodeUtils
 * @projectName upload
 * @description: TODO
 * @date 2021/7/3 0003
 */
public class ZXingCodeEncodeUtils {
    // 二维码颜色
    private static final int BLACK = 0xFF000000;
    // 二维码背景颜色
    private static final int WHITE = 0xFFFFFFFF;
    // 二维码格式参数
    private static final EnumMap<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);

    static {
        /**
         * 二维码纠错级别（排错率），4个级别：L（7%）、M（15%）、Q（25%）、H（30%），最高设置为H
         */
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 二维码边界空白大小,内容编码格式
        hints.put(EncodeHintType.MARGIN, 1);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    }

    public static void main(String[] args) {
//        try {
//            createZXingCodeSaveToDisk("测试一个二维码", 400, 400, "E:/upload/zxing.png", "JPEG");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        String scen1 = "{\"name\":\"夏一翔\",\"sex\":\"男\",\"age\":\"23\"}";
        String username = "测试名";
        String sex = "女";
        int old = 22;
        String scen2 = "{\"name\":\"" + username + "\",\"sex\":\"" + sex + "\",\"age\":\"" + old + "\"}";
        System.out.println("scen1:" + scen1);
        System.out.println("scen2:" + scen2);
    }

    /**
     * 生成二维码并写入到磁盘
     *
     * @param content
     * @param width
     * @param height
     * @param savePath
     * @param imageType
     */
    public static void createZXingCodeSaveToDisk(String content, int width, int height, String savePath, String imageType) throws IOException {
        try {
            BitMatrix encode = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int code_width = encode.getWidth();
            int code_height = encode.getHeight();
            // 创建图片
            BufferedImage bufferedImage = new BufferedImage(code_width, code_height, BufferedImage.TYPE_INT_BGR);
            // 把二维码里面的信息写入到图片中
            for (int i = 0; i < code_width; i++) {
                for (int j = 0; j < code_height; j++) {
                    bufferedImage.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
                }
            }
            // 保存图片到硬盘中
            File file = new File(savePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            ImageIO.write(bufferedImage, imageType, file);
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成二维码并返回图片
     *
     * @param content
     * @param width
     * @param height
     */
    public static BufferedImage createZXingCodeNormal(String content, int width, int height) {
        try {
            BitMatrix encode = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int code_width = encode.getWidth();
            int code_height = encode.getHeight();
            // 创建图片
            BufferedImage bufferedImage = new BufferedImage(code_width, code_height, BufferedImage.TYPE_INT_BGR);
            // 把二维码里面的信息写入到图片中
            for (int i = 0; i < code_width; i++) {
                for (int j = 0; j < code_height; j++) {
                    bufferedImage.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
                }
            }
            return bufferedImage;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 输入二维码返回一张带logo的二维码
     *
     * @param matrixImage 原始二维码
     * @return
     * @throws IOException
     */
    public static BufferedImage LogoMatrix(BufferedImage matrixImage) throws IOException {
        // 构建二维码图片，并构建绘图对象
        Graphics2D graphics = (Graphics2D) matrixImage.getGraphics();
        int matrixWidth = matrixImage.getWidth();
        int matrixHeight = matrixImage.getHeight();
        // 读取logo图片
        BufferedImage logo = ImageIO.read(new File("F:\\图片\\logo.jpg"));
        // 开始绘制图片
        graphics.drawImage(logo, matrixWidth / 5 * 2, matrixHeight / 5 * 2, matrixWidth / 5, matrixHeight / 5, null);
        BasicStroke stroke = new BasicStroke(5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        //设置笔画对象
        graphics.setStroke(stroke);
        // 制定弧度的圆角矩形
        RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth / 5 * 2, matrixHeight / 5 * 2, matrixWidth / 5, matrixHeight / 5, 20, 20);
        graphics.setColor(Color.white);
        graphics.draw(round);
        //设置logo有一道白色边框
        BasicStroke stroke2 = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        graphics.setStroke(stroke2);// 设置笔画对象
        RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth / 5 * 2 + 2, matrixHeight / 5 * 2 + 2, matrixWidth / 5 - 4, matrixHeight / 5 - 4, 20, 20);
        graphics.setColor(new Color(128, 128, 128));
        // 绘制圆弧矩形
        graphics.draw(round2);
        graphics.dispose();
        matrixImage.flush();
        return matrixImage;
    }
}
